$(document).ready(function(){
    //$('#left-container').hide("slide", { direction: "right" }, 1000);
    $('.pesquisa').button().click(function(){
            $('form').submit();});
    $.ajaxSetup({
        cache: false,
        type: 'POST',
        dataType: 'json',
        error: function () {
            alert('Um erro de comunicação com o servidor ocorreu!');
            $('#ajax-ldr').fadeOut('fast');
            $('#wait').fadeOut('fast');
        }
    });

    $('.tips').tipsy({
        title:'obs',
        gravity: $.fn.tipsy.autoNS,
        delayIn:1000,
        delayOut:500,
        html:true
    });
    $(".data").datepicker({
        monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
        dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
        dateFormat: 'dd/mm/yy'
    });
    $("#dialog").dialog({
        dialogClass: 'alert',
        draggable: true,
        modal: true,
        title: 'Informações sobre o Trabalho',
        resizable: true,
        show: 'fadeIn',
        autoSize: true,
        autoOpen: false,
        minWidth: 350,
        width: 350,
        close: function(event, ui) {
            $('#descricao').val('');$('#nome_rotina').val('');
            $('#datatrab').val('');$('#controller').val('');
            $('#action').val('');$('#horas').val('');
            $('#minutos').val('');$('#rotina_id').val('');
            $('.error').hide();
        },
        buttons: {
            'Criar':function(){
                $.ajax({
                    url: "/tasks/trabalhar",
                    processData: false,
                    data: 'tarefa_id='+$('#tarefa_id').val()+'&descricao='+$('#descricao').val()+'&user_id='+$('#user_id').val()+
                    '&rotina_id='+$('#rotina_id').val()+'&horas='+$('#horas').val()+'&minutos='+$('#minutos').val()+
                    '&data='+$('#datatrab').val()+'&controller='+$('#controller').val()+'&action='+$('#action').val()+
                    '&nome_rotina='+$('#nome_rotina').val()+'&model='+$('#model').val()+'&views='+$('#views').val(),
                    beforeSend: function (){
                        //                        var pos = $("#trab_"+tarefa).position();
                        //                       var width = $("#trab_"+tarefa).width();
                        //                      $("#ajax-ldr").css( {
                        //                         "left": (pos.left+width+5) + "px",
                        //                        "top":pos.top + "px"
                        //                   } ).fadeIn('fast');
                        $("#wait").fadeIn('fast').html('Fechando Tarefa...');
                    },
                    success: function(msg){
                        $('#ajax-ldr').fadeOut('fast');
                        $("#wait").fadeOut('fast');
                        if (msg==true){
                            $('#dialog').dialog('close');
                            $('#descrical').val('');$('#nome_rotina').val('');
                            $('#data').val('');$('#controller').val('');
                            $('#action').val('');$('#horas').val('');
                            $('#minutos').val('');$('#rotina_id').val('');
                            $('.error').hide();
                        }
                        else{
                            $('.error').hide();
                            $.each(msg,function(key,value){
                                showError(key, value);
                            });
                        }
                    }
                });
            },
            'Cancelar': function(){
                $('#dialog').dialog('close');
                $('#dialog').dialog('close');
                $('#descricao').val('');$('#nome_rotina').val('');
                $('#data').val('');$('#controller').val('');
                $('#action').val('');$('#horas').val('');
                $('#minutos').val('');$('#rotina_id').val('');
                $('.error').hide();
                return false;
            }
        }
    });
    $(".messages").fadeOut(6500);
    $('#accordion').accordion();
    $('#tabs').tabs();
    $('.trabalho').change(function(){
        var tarefa = $(this).attr('tar_id');
        var estado = $(this).val();
        //alert(tarefa);
        $.ajax({
            url: "/tasks/alocar",
            processData: false,
            data: 'id='+tarefa+'&estado_id='+estado,
            beforeSend: function (){
                var pos = $("#select_"+tarefa).position();
                var width = $("#select_"+tarefa).width();
                $("#ajax-ldr").css( {
                    "left": (pos.left+width+5) + "px",
                    "top":pos.top + "px"
                } ).fadeIn('fast');
                $("#wait").fadeIn('fast').html('Fechando Tarefa...');
            },
            success: function(msg){
                $('#ajax-ldr').fadeOut('fast');
                $("#wait").fadeOut('fast');
                if (msg == false){
                    return false;
                }
            }
        });

    });
    $('.trabalhar').click(function(){
        $('#tarefa_id').val($(this).attr('tar_id'));
        $('#dialog').dialog('open');
        return false;
    });
    $('#nome_rotina').autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "/rotinas/index",
                type: "POST",
                datatype: "json",
                data: {
                    q: request.term
                },
                success: function(data) {
                    //alert(data);
                    response($.map(data, function(item) {
                        return {
                            label: item.nome +'('+item.codsis+')',
                            value: item.id_rotina
                        }
                    }))
                }
            })
        },
        focus: function(event,ui){
            $('#rotina_id').val(ui.item.label);
            return false;
        },
        open: function(event,ui) {
            $('#rotina_id').val('');
        },
        select: function(event,ui){
            //alert(ui.item.label);
            $('#rotina_id').val(ui.item.value);
            $('#nome_rotina').val(ui.item.label);
            return false;
        },
        minChars : 3
    });
    function showError(key,val)
    {
        var formElement = $('#'+key);
        var container = formElement.next('.error');
        if (container){
            //alert(key);
            var valor = '';
            $.each(val, function(key,value){
               valor += '<li>'+value+'</li>';
            });
            container.html('');
            container.html($('<div>')
                                .attr('class','ui-state-error ui-corner-all')
                                .html(
                                    $('<span>')
                                        .attr('class','ui-icon ui-icon-alert')
                                        .attr('style','float: left; margin-right: 0.3em;'))
                                .append(valor)
                           );
            container.show();
        }
    }
    $('#equipe_id').change(function(){
        $.ajax({
            url: "/sprints/index",
            processData: false,
            data: 'equipe_id='+$('#equipe_id').val(),
            beforeSend: function (){
                var pos = $("#equipe_id").position();
                var width = $("#equipe_id").width();
                $("#ajax-ldr").css( {
                    "left": (pos.left+width+5) + "px",
                    "top":pos.top + "px"
                } ).fadeIn('fast');
            },
            success: function(msg){
                $('#ajax-ldr').fadeOut('fast');
                $("#wait").fadeOut('fast');
                if (msg == false){
                    return false;
                }else{
                    $('#sprint_id option').remove();
                    $('#sprint_id').append($('<option>').attr('value','').attr('text','Selecione o Sprint'));
                    $.each(msg, function(i,k){
                        $('#sprint_id').append($('<option>').attr('value',k.id).attr('text',k.id+') '+k.descricao+' - '+'Final ('+k.data_fim+')'));
                    } );
                }
            }
        });
    });
    $('.documentar').click(function(){

        var tar = $(this).attr('tar_id');
        var spr = $(this).attr('sprint_id');
        var bak = $(this).attr('backlog_id');
        var cha = $(this).attr('chamada_id');
        var e   = this;
        
        $.ajax({
            url: "/doctotask/documentar",
            processData: false,
            data: 'task_id='+tar,
            type: 'get',
            beforeSend: function (){
                var pos = $(e).position();
                var width = $(e).width();
                $("#ajax-ldr").css( {
                    "left": (pos.left+width+5) + "px",
                    "top":pos.top + "px"
                } ).fadeIn('fast');
            },
            success: function(msg){
          //      if (msg == false){
          //          return false;
          //      }
                $('#ajax-ldr').fadeOut('fast');
                //alert(msg);
                //$('#documenta').html(msg);
                $('#task_id').val(tar);
                $('#sprint_id').val(spr);
                $('#backlog_id').val(bak);
                $('#chamada_id').val(cha);
                $('#documentacao').val(msg.documentacao);
                $('#dlgdocumenta').dialog('open');
                $('#documentacao').ckeditor({toolbar : 'Full', language:'pt-br', themes:'default',
                    toolbar:[
                                {name: 'document', items : [ 'NewPage','Preview' ]},
                                {name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ]},
                                {name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','Scayt' ]},
                                {name: 'insert', items : [ 'Image','Table','HorizontalRule','SpecialChar','PageBreak' ]},
                                {name: 'styles', items : [ 'Styles','Format','Font','FontSize','TextColor','BGColor' ]},
                                {name: 'basicstyles', items : [ 'Bold','Italic','Strike','-','RemoveFormat' ]},
                                {name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote' ]},
                            ]
                });
            }
        });
        return false; 
    });
    
    $("#dlgdocumenta").dialog({
        dialogClass: 'info',
        draggable: true,
        modal: true,
        title: 'Documentação da Modificação',
        resizable: true,
        show: 'fadeIn',
        autoSize: false,
        autoOpen: false,
        minWidth: 750,
        width: 750,
        close: function(){ $('#documentacao').ckeditorGet().destroy();},
        buttons: {
            'Criar':function(){
                $.ajax({
                    url: "/doctotask/documentar",
                    processData: false,
                    type:'post',
                    data: 'task_id='+$('#task_id').val()+'&documentacao='+escape($('#documentacao').val())+'&sprint_id='+$('#sprint_id').val()+'&backlog_id='+$('#backlog_id').val()+'&chamada_id='+$('#chamada_id').val(),
                    beforeSend: function (){
                        //$("#wait").fadeIn('fast').html('Fechando Tarefa...');
                        //$(this).attr('enabled',false);
                    },
                    success: function(msg){
                        if (msg==true){
                            $('#dlgdocumenta').dialog('close');
                            $('#documentacao').val('');
                            $('#task_id').val('');
                            $('#sprint_id').val('');
                            $('#backlog_id').val('');
                            $('#chamada_id').val('');
                            $('.error').hide();
                            $(this).attr('enabled',true);
                        }
                        else{
                            $('.error').hide();
                            $.each(msg,function(key,value){
                                showError(key, value);
                            });
                        }
                        $("#wait").fadeOut('fast');
                    }
                });
            },
            'Cancelar': function(){
                $('#dlgdocumenta').dialog('close');
                $('#documentacao').val('');
                $('#task_id').val('');
                $('#sprint_id').val('');
                $('#backlog_id').val('');
                $('#chamada_id').val('');
                $('.error').hide();
                return false;
            }
        }
    });
});